<?php
namespace service;

use think\Cache;
use app\common\model as M;
/**
 * 微信视频号开放能力服务
 * @see https://developers.weixin.qq.com/doc/channels/API/product/list_get.html
 * Class WechatPayV3Service
 * @package service
 */

class WechatChannel
{
    protected $appid;
    protected $apiKey;
    protected $baseUrl = 'https://api.weixin.qq.com';
	
    public function __construct()
    {
        $this->appid = \think\Env::get('WECHATCHANNEL.APP_ID');
        $this->apiSecret = \think\Env::get('WECHATCHANNEL.APP_SECRET');
    }
	
	/**
     * [getAccessToken description]
     * @Author   FW
     * @DateTime 2021-04-08
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function getAccessToken ()
    {
        $accessToken = Cache::get('WechatChannelAccessToken');
        if ( empty($accessToken) ) {
            $params  = sprintf('/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s', $this->appid,$this->apiSecret);
            $result  = json_decode($this->curlGet( $this->baseUrl . $params),true);

            if ( isset($result['access_token']) ) {
                $accessToken = $result['access_token'];
                Cache::set('WechatChannelAccessToken',$accessToken, $result['expires_in']);
            }
        }
        return $accessToken;
    }

    /**
     * 添加商品
     */  
    public function addProduct($routeId)
    {
        $productInfo = [];
        $routeInfo = M\Routes::where('id',$routeId)->find();

        $productInfo['out_product_id'] = (string)$routeInfo->id;
        $productInfo['title'] = $routeInfo->route_name;
        $productInfo['head_imgs'] = array_merge([$routeInfo->cover],json_decode($routeInfo->albums,true));
        
        //固定为 旅游休闲->本地玩乐->滑雪场
        $productInfo['cats'] =[
            ['cat_id' => 128209],
            ['cat_id' => 428007],
            ['cat_id' => 526044],
        ];

        $productInfo['attrs'] = [
            [
                'attr_key'  => '最小起订',
                'attr_value'=> $routeInfo->min_sold_num . '人起'
            ]
        ];
        if ( $routeInfo->start_address ) {
            $productInfo['attrs'][] = [
                'attr_key'  => '出发地点',
                'attr_value'=> $routeInfo->start_address
            ];
        }
        if ( $routeInfo->end_address ) {
            $productInfo['attrs'][] = [
                'attr_key'  => '结束地点',
                'attr_value'=> $routeInfo->end_address
            ];
        }
        if ( $routeInfo->is_gift_insurance > 0 ) {
            $productInfo['attrs'][] = [
                'attr_key'  => '出行险',
                'attr_value'=> '赠送'
            ];
        }
        if ( $routeInfo->is_refund_whatever > 0 ) {
            $productInfo['attrs'][] = [
                'attr_key'  => '随时退',
                'attr_value'=> '支持'
            ];
        }

        $productInfo['extra_service']['seven_day_return'] = 1;
        $productInfo['extra_service']['pay_after_use'] = 1;
        $productInfo['extra_service']['freight_insurance'] = 0;

        $routeSkus = M\RoutesSku::where('route_id',$routeInfo->id)->select();
        $productInfo['skus'] = [];
        foreach ( $routeSkus as $routeSku ) {
            $salePrice = M\RoutesSkuPrice::where('route_id',$routeInfo->id)->where('sku_id',$routeSku->id)->order('date asc')->limit(1)->find();
            $productInfo['skus'][] = [
                'out_sku_id' => (string)$routeSku->id,
                'sale_price' => $salePrice->price * 100,
                'stock_num'  => $salePrice->left_store,
                'sku_attrs'  => [
                    [
                        'attr_key'   => 'attr_key',
                        'attr_value' => 'attr_value',
                    ]
                ]
            ];
        }
        return json_decode($this->curlPost( $this->baseUrl . '/channels/ec/product/add?access_token=' . $this->getAccessToken() ,json_encode($productInfo)),true);
    }

    /**
     * 获取商品列表
     */  
    public function getProductList($page_size = 10, $status = 0 ,  $next_key = '' )
    {
        if ( !$page_size ) $page_size = 10;
        $params = [
            'page_size' => $page_size,
        ];
        if ( $status > 0 ) $params['status'] = $status;
        if ( $next_key ) $params['next_key'] = $next_key;

        return json_decode($this->curlPost( $this->baseUrl . '/channels/ec/product/list/get?access_token=' . $this->getAccessToken() ,json_encode($params)),true);
    }

    public function getCategoryList()
    {
        return json_decode($this->curlGet( $this->baseUrl . '/channels/ec/category/all?access_token=' . $this->getAccessToken()));
    }

    /**
     * curl get
     *
     * @param string $url
     * @param array $options
     * @return mixed
     */
    public function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}